<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>登录 - 翻译助手</title>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #f8f9fa;
            min-height: 100vh;
            display: flex;
            align-items: center;
        }
        .auth-container {
            max-width: 400px;
            margin: 0 auto;
            padding: 20px;
        }
        .card {
            border: none;
            box-shadow: 0 0 20px rgba(0,0,0,0.1);
            border-radius: 15px;
        }
        .card-header {
            background: none;
            border-bottom: none;
            padding-top: 20px;
        }
        .btn-lg {
            min-width: 120px;
            padding: 12px 24px;
            font-weight: 500;
        }
        .form-control {
            padding: 12px;
            border-radius: 8px;
        }
        .form-label {
            font-weight: 500;
            color: #495057;
        }
        .form-text {
            color: #6c757d;
        }
        .btn-primary {
            background-color: #0d6efd;
            border: none;
            transition: all 0.3s;
        }
        .btn-primary:hover {
            background-color: #0b5ed7;
            transform: translateY(-1px);
        }
        .btn-outline-primary:hover {
            transform: translateY(-1px);
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-6 mt-5">
                <!-- 按钮组 -->
                <div class="d-flex justify-content-center gap-3 mb-4">
                    <button class="btn btn-primary btn-lg px-5" id="showLoginBtn">登录</button>
                    <button class="btn btn-outline-primary btn-lg px-5" id="showRegisterBtn">注册</button>
                </div>

                <!-- 登录表单 -->
                <div class="card" id="loginCard" style="display: none;">
                    <div class="card-header text-center">
                        <h4>用户登录</h4>
                    </div>
                    <div class="card-body">
                        <form id="loginForm">
                            <div class="mb-3">
                                <label for="loginIdentifier" class="form-label">用户名/邮箱/手机号</label>
                                <input type="text" class="form-control" id="loginIdentifier" required>
                            </div>
                            <div class="mb-3">
                                <label for="loginPassword" class="form-label">密码</label>
                                <input type="password" class="form-control" id="loginPassword" required>
                            </div>
                            <div class="mb-3 form-check">
                                <input type="checkbox" class="form-check-input" id="rememberMe">
                                <label class="form-check-label" for="rememberMe">记住我</label>
                            </div>
                            <div class="d-grid">
                                <button type="submit" class="btn btn-primary">登录</button>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- 注册表单 -->
                <div class="card" id="registerCard" style="display: none;">
                    <div class="card-header text-center">
                        <h4>用户注册</h4>
                    </div>
                    <div class="card-body">
                        <form id="registerForm">
                            <div class="mb-3">
                                <label for="registerUsername" class="form-label">用户名</label>
                                <input type="text" class="form-control" id="registerUsername" required>
                                <div class="form-text">必填，用于登录</div>
                            </div>
                            <div class="mb-3">
                                <label for="registerFullName" class="form-label">姓名</label>
                                <input type="text" class="form-control" id="registerFullName" required>
                                <div class="form-text">必填，您的真实姓名</div>
                            </div>
                            <div class="mb-3">
                                <label for="registerEmail" class="form-label">邮箱</label>
                                <input type="email" class="form-control" id="registerEmail">
                                <div class="form-text">选填，可用于登录</div>
                            </div>
                            <div class="mb-3">
                                <label for="registerPhone" class="form-label">手机号</label>
                                <input type="tel" class="form-control" id="registerPhone" 
                                       pattern="[0-9]{11}" placeholder="请输入11位手机号">
                                <div class="form-text">选填，可用于登录</div>
                            </div>
                            <div class="mb-3">
                                <label for="registerPassword" class="form-label">密码</label>
                                <input type="password" class="form-control" id="registerPassword" required>
                                <div class="form-text">必填，请设置登录密码</div>
                            </div>
                            <div class="mb-3">
                                <label for="confirmPassword" class="form-label">确认密码</label>
                                <input type="password" class="form-control" id="confirmPassword" required>
                                <div class="form-text">必填，请再次输入密码</div>
                            </div>
                            <div class="d-grid">
                                <button type="submit" class="btn btn-primary">注册</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

    <script>
    document.addEventListener('DOMContentLoaded', () => {
        const loginCard = document.getElementById('loginCard');
        const registerCard = document.getElementById('registerCard');
        const showLoginBtn = document.getElementById('showLoginBtn');
        const showRegisterBtn = document.getElementById('showRegisterBtn');
        const loginForm = document.getElementById('loginForm');
        const registerForm = document.getElementById('registerForm');
        
        const API_BASE_URL = 'http://localhost:8000/api/v1';

        // 初始显示登录表单
        showLoginBtn.classList.add('active');
        loginCard.style.display = 'block';

        // 添加全局fetch错误处理
        const fetchWithError = async (url, options) => {
            try {
                const response = await fetch(url, options);
                const contentType = response.headers.get('content-type');
                let data;
                
                if (contentType && contentType.includes('application/json')) {
                    data = await response.json();
                } else {
                    throw new Error('服务器返回的不是JSON格式数据');
                }
                
                if (!response.ok) {
                    console.error('服务器返回错误:', data);
                    throw new Error(data.detail || data.message || '请求失败');
                }
                
                return data;
            } catch (error) {
                if (error.name === 'TypeError' && error.message === 'Failed to fetch') {
                    throw new Error('无法连接到服务器，请检查网络连接或服务器状态');
                }
                throw error;
            }
        };

        // 表单数据验证
        const validateLoginForm = (identifier, password) => {
            if (!identifier || identifier.trim() === '') {
                throw new Error('请输入用户名/邮箱/手机号');
            }
            if (!password || password.trim() === '') {
                throw new Error('请输入密码');
            }
            if (password.length < 6) {
                throw new Error('密码长度不能少于6位');
            }
        };

        // 切换显示登录表单
        showLoginBtn.addEventListener('click', () => {
            loginCard.style.display = 'block';
            registerCard.style.display = 'none';
            showLoginBtn.classList.add('btn-primary');
            showLoginBtn.classList.remove('btn-outline-primary');
            showRegisterBtn.classList.add('btn-outline-primary');
            showRegisterBtn.classList.remove('btn-primary');
        });

        // 切换显示注册表单
        showRegisterBtn.addEventListener('click', () => {
            loginCard.style.display = 'none';
            registerCard.style.display = 'block';
            showRegisterBtn.classList.add('btn-primary');
            showRegisterBtn.classList.remove('btn-outline-primary');
            showLoginBtn.classList.add('btn-outline-primary');
            showLoginBtn.classList.remove('btn-primary');
        });

        // 处理注册表单提交
        registerForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const username = document.getElementById('registerUsername').value;
            const fullName = document.getElementById('registerFullName').value;
            const email = document.getElementById('registerEmail').value;
            const phone = document.getElementById('registerPhone').value;
            const password = document.getElementById('registerPassword').value;
            const confirmPassword = document.getElementById('confirmPassword').value;

            // 表单验证
            if (password !== confirmPassword) {
                alert('两次输入的密码不一致');
                return;
            }

            if (password.length < 6) {
                alert('密码长度不能少于6位');
                return;
            }

            try {
                console.log('发送注册请求:', {
                    url: `${API_BASE_URL}/admin/users/`,
                    data: {
                        username,
                        full_name: fullName,
                        email: email || null,
                        phone: phone || null,
                        password: '***'
                    }
                });

                // 注册新用户
                const response = await fetch(`${API_BASE_URL}/admin/users/`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json'
                    },
                    body: JSON.stringify({
                        username: username.trim(),
                        full_name: fullName.trim(),
                        email: email.trim() || null,
                        phone: phone.trim() || null,
                        password: password
                    })
                });

                const data = await response.json();

                if (!response.ok) {
                    throw new Error(data.message || data.detail || '注册失败');
                }

                console.log('注册响应:', {
                    success: data.success,
                    message: data.message
                });

                alert('注册成功，请登录');
                // 清空表单
                registerForm.reset();
                // 切换到登录表单
                showLoginBtn.click();
                
            } catch (error) {
                console.error('注册错误:', error);
                alert(error.message || '注册失败，请重试');
            }
        });

        // 处理登录表单提交
        loginForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const identifier = document.getElementById('loginIdentifier').value;
            const password = document.getElementById('loginPassword').value;
            const rememberMe = document.getElementById('rememberMe').checked;

            try {
                // 表单验证
                validateLoginForm(identifier, password);

                // 准备请求数据
                const loginData = {
                    username: identifier.trim(),
                    password: password
                };

                console.log('发送登录请求:', {
                    url: `${API_BASE_URL}/auth/login`,
                    data: { ...loginData, password: '***' }
                });

                const data = await fetchWithError(`${API_BASE_URL}/auth/login`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json'
                    },
                    body: JSON.stringify(loginData)
                });
                
                console.log('登录响应:', {
                    success: data.success,
                    message: data.message,
                    hasToken: !!data.access_token,
                    hasUser: !!data.user
                });

                // 保存认证信息
                if (data.access_token) {
                    localStorage.setItem('access_token', data.access_token);
                    localStorage.setItem('token_type', data.token_type || 'bearer');
                    if (data.user) {
                        localStorage.setItem('user_info', JSON.stringify(data.user));
                        localStorage.setItem('username', data.user.username);
                    }
                    
                    if (rememberMe) {
                        localStorage.setItem('remember_me', 'true');
                    }

                    alert('登录成功！');
                    // 修改跳转目标为首页
                    window.location.href = '../index.html';
                } else {
                    throw new Error('登录失败：服务器响应中缺少访问令牌');
                }
                
            } catch (error) {
                console.error('登录错误:', error);
                alert(error.message || '登录失败，请检查用户名和密码');
            }
        });
    });
    </script>
</body>
</html> 